package cn.kgc.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * 原生RabbitMQAPI的工具类
 *
 * @author YC
 */
public class RabbitConnectUtil {

    private static final GenericObjectPool<Connection> connectionPool;
    private static final String host = "127.0.0.1";
    private static final int port = 5672;
    private static final String username = "guest";
    private static final String password = "guest";
    private static final String virtualHost = "/";


    static {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        //最大连接数
        poolConfig.setMaxTotal(20);
        // 当连接耗尽时是否阻塞
        poolConfig.setBlockWhenExhausted(true);
        connectionPool = new GenericObjectPool<>(new ConnectionPoolFactory(), poolConfig);
    }


    public static Connection getConnection() throws Exception {
        return connectionPool.borrowObject();
    }


    public static void returnConnection(Connection connection) {
        connectionPool.returnObject(connection);
    }


    private static class ConnectionPoolFactory extends BasePooledObjectFactory<Connection> {
        @Override
        public Connection create() throws Exception {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setVirtualHost(virtualHost);
            factory.setHost(host);
            factory.setPort(port);
            factory.setUsername(username);
            factory.setPassword(password);
            return factory.newConnection();
        }


        @Override
        public PooledObject<Connection> wrap(Connection connection) {
            return new DefaultPooledObject<>(connection);
        }
    }
}